package com.member.shop.service.impl;

import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.constant.Constants;
import com.member.common.core.domain.model.LoginUser;
import com.member.common.enums.*;
import com.member.common.exception.ServiceException;
import com.member.common.utils.*;
import com.member.common.utils.bean.BeanUtils;
import com.member.common.utils.http.HttpUtils;
import com.member.common.utils.newIp.IpUtils;
import com.member.shop.domain.*;
import com.member.shop.dto.*;
import com.member.shop.mapper.*;
import com.member.shop.service.*;
import com.member.shop.vo.*;
import com.member.system.cache.TokenCache;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.member.common.utils.SecurityUtils.getLoginUser;

/**
 * 管理员列表Service业务层处理
 *
 * @author lixinchen
 * @date 2024-12-28
 */
@Slf4j
@Service
public class SysBizUserServiceImpl extends ServiceImpl<SysBizUserMapper, SysBizUser> implements ISysBizUserService {
    @Resource
    private SysBizUserMapper sysBizUserMapper;
    @Resource
    private SysBizOperationLogMapper sysBizOperationLogMapper;
    @Resource
    private ISysBizMemberGradeService sysBizMemberGradeService;
    @Resource
    private ISysBizOrderService sysBizOrderService;
    @Resource
    private ISysBizWithdrawApplyService sysBizWithdrawApplyService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private ISysBizCouponReceiveService sysBizCouponReceiveService;
    @Resource
    private ISysBizGradeLogService sysBizGradeLogService;

    @Resource
    private SysBizRechargeUserMapper sysBizRechargeUserMapper;

    @Resource
    private SysBizUserSurplusDetailsMapper sysBizUserSurplusDetailsMapper;

    @Resource
    private SysBizCouponMapper sysBizCouponMapper;

    @Resource
    private SysBizCouponGrantMapper sysBizCouponGrantMapper;

    @Resource
    private SysBizCouponGrantUserMapper sysBizCouponGrantUserMapper;

    @Resource
    private SysBizCouponReceiveMapper sysBizCouponReceiveMapper;

    private final ReentrantLock lock = new ReentrantLock();

    @Resource
    private ISysBizTenantService sysBizTenantService;

    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;


    @Value("${coupon.getUser}")
    private String getUserUrl;


    @Value("${coupon.returnUrl}")
    private String returnUrl;

    /**
     * 查询管理员列表
     *
     * @param id 管理员列表主键
     * @return 管理员列表
     */
    @Override
    public SysBizUser selectSysBizUserById(Long id) {
        return sysBizUserMapper.selectById(id);
    }

    /**
     * 查询用户列列表
     *
     * @param queryWrapper 用户列
     * @return 用户列
     */
    @Override
    public List<SysBizUser> selectSysBizUserList(LambdaQueryWrapper<SysBizUser> queryWrapper) {
        return sysBizUserMapper.selectList(queryWrapper);
    }

    /**
     * 查询管理员列表列表
     *
     * @param sysBizUser 管理员列表
     * @return 管理员列表
     */
    @Override
    public List<SysBizUser> selectSysBizUserList(SysBizUser sysBizUser) {
        return sysBizUserMapper.selectSysBizUserList(sysBizUser);
    }

    /**
     * 新增管理员列表
     *
     * @param sysBizUser 管理员列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSysBizUser(SysBizUser sysBizUser) {
        sysBizUser.setCreateTime(DateUtils.getNowDate());
        String KEY = "INVITATION_CODE";
        List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
        if (!CollectionUtils.isEmpty(list) && list.size() >= 9999999) {
            log.error("邀请码满员");
        }
        String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
        if (!CollectionUtils.isEmpty(list)) {
            do {
                code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
            } while (list.contains(code) || Objects.equals(code, sysBizUser.getInvitationCode()));
        }
        redisTemplate.opsForList().leftPush(KEY, code);
        sysBizUser.setInvitationCode(code);
        // 查询上级
        if (StringUtils.isNotBlank(sysBizUser.getParentPhone())) {
            SysBizUser parentUser = sysBizUserMapper.selectOne(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getUserPhone, sysBizUser.getParentPhone()).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
            if (parentUser == null) {
                throw new ServiceException("上级手机号不存在");
            }
            sysBizUser.setParentId(parentUser.getId());
        }
        sysBizUser.setPassword(SecurityUtils.encryptPassword(sysBizUser.getUserPhone()));
        int insert = sysBizUserMapper.insert(sysBizUser);
        sysBizUserMapper.updateBizId(sysBizUser.getId());
        SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
        sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
        sysBizOperationLog.setOperationItem(OperationItemEnum.ADD_MEMBERS.getKey());
        sysBizOperationLog.setOperationDetails("添加会员【" + sysBizUser.getUserPhone() + "】");
        sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
        sysBizOperationLogMapper.insert(sysBizOperationLog);
        return insert;
    }

    /**
     * 修改管理员列表
     *
     * @param sysBizUser 管理员列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSysBizUser(SysBizUser sysBizUser) throws IOException {
        SysBizUser user = sysBizUserMapper.selectById(sysBizUser.getId());
        sysBizUser.setUpdateTime(DateUtils.getNowDate());
        //如果还不是会员
        if (sysBizUser.getUserRole() != null && !sysBizUser.getUserRole().equals(StandingEnum.IS_MEMBER.getKey())) {
            //日志表
//            if (StringUtils.isNotBlank(sysBizUser.getIdCard())) {
//                // 实名验证start
//                Map<String, String> params = new HashMap<>();
//                params.put("idcard", sysBizUser.getIdCard());
//                params.put("name", sysBizUser.getFullName());
//                String result = postForm(appCode, url, params);
//                JSONObject resultData = JSON.parseObject(result);
//                if (!"0".equals(resultData.get("code"))) {
//                    throw new ServiceException(resultData.get("message").toString());
//                }
//                JSONObject jsonObject = JSON.parseObject(resultData.get("result").toString());
//                if ("2".equals(jsonObject.get("res").toString())) {
//                    throw new ServiceException("姓名与身份证号不一致");
//                }
//                if (!"1".equals(jsonObject.get("res").toString())) {
//                    throw new ServiceException(jsonObject.get("description").toString());
//                }
//                List<SysBizUser> users = sysBizUserMapper.selectList(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getIdCard,
//                        sysBizUser.getIdCard()));
//                if (!CollectionUtils.isEmpty(users)) {
//                    throw new ServiceException("身份证号码已存在");
//                }
//                // 实名验证end
//            }
            LoginUser loginUser = SecurityUtils.getLoginUser();
            SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();
            sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
            sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
            sysBizOperationLog.setOperationItem(OperationItemEnum.ADD_MEMBERS.getKey());
            sysBizOperationLog.setOperationDetails("添加会员【" + sysBizUser.getUserPhone() + "】");
            sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
            sysBizOperationLogMapper.insert(sysBizOperationLog);
            if (sysBizUser.getProcessStatus().equals(ProcessStatusEnum.UN_PROCESS.getKey()) || sysBizUser.getProcessStatus().equals(ProcessStatusEnum.NOT_PASS_PROCESS.getKey())) {
                sysBizUser.setProcessStatus(ProcessStatusEnum.PASS_PROCESS.getKey());
                sysBizUser.setIsRegisterMember(1);
                sysBizUser.setProcessTime(DateUtils.getNowDate());
            }
        }
        if (sysBizUser.getRechargeBalance() != null && !sysBizUser.getRechargeBalance().equals(BigDecimal.ZERO)) {
            SysBizUser sysBizUser1 = sysBizUserMapper.selectById(sysBizUser.getId());
            BigDecimal rechargeBalance;
            BigDecimal add;
            String text = "";
            if (sysBizUser.getType() == 0) {
                rechargeBalance = sysBizUser1.getRechargeBalance().add(sysBizUser.getRechargeBalance());
                add = sysBizUser1.getUnwithdrawnBalance().add(sysBizUser.getRechargeBalance());
                text = "增加";
            } else if (sysBizUser1.getUnwithdrawnBalance().compareTo(sysBizUser.getRechargeBalance()) < 0) {
                throw new ServiceException("分账金不足");
            } else {
                rechargeBalance = sysBizUser1.getRechargeBalance().subtract(sysBizUser.getRechargeBalance());
                add = sysBizUser1.getUnwithdrawnBalance().subtract(sysBizUser.getRechargeBalance());
                text = "减少";
            }
            //会员充值
            SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();
            LoginUser loginUser = SecurityUtils.getLoginUser();
            sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
            sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
            sysBizOperationLog.setOperationItem(OperationItemEnum.MEMBER_RECHARGE.getKey());
            sysBizOperationLog.setOperationDetails("会员充值" + text + "【" + sysBizUser.getUserPhone() + "+" + sysBizUser.getFullName() + "+￥" + sysBizUser.getRechargeBalance() + "】");
            sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
            sysBizOperationLogMapper.insert(sysBizOperationLog);


            sysBizUser.setRechargeBalance(rechargeBalance);
            sysBizUser.setUnwithdrawnBalance(add);
        }
        sysBizUser.setUserRole(StandingEnum.IS_MEMBER.getKey());
        // 等级变更记录
        if ((user.getMemberGradeId() == null && sysBizUser.getMemberGradeId() != null) || (user.getMemberGradeId() != null && sysBizUser.getMemberGradeId() != null && !user.getMemberGradeId().equals(sysBizUser.getMemberGradeId()))) {
            String oldGradeName = "";
            String newGradeName = "";
            if (sysBizUser.getMemberGradeId() != null) {
                SysBizMemberGrade byId = sysBizMemberGradeService.getById(sysBizUser.getMemberGradeId());
                if (byId != null) {
                    newGradeName = byId.getGradeName();
                }
            }
            if (user.getMemberGradeId() != null) {
                SysBizMemberGrade byId = sysBizMemberGradeService.getById(user.getMemberGradeId());
                if (byId != null) {
                    oldGradeName = byId.getGradeName();
                }
            }
            sysBizGradeLogService.save(SysBizGradeLog.builder().userId(user.getId()).gradeIdOld(user.getMemberGradeId()).gradeIdNew(sysBizUser.getMemberGradeId()).gradeNameOld(oldGradeName).gradeNameNew(newGradeName).createBy(SecurityUtils.getUsername()).createTime(DateUtils.getNowDate()).build());
        }
        return sysBizUserMapper.updateById(sysBizUser);
    }

    /**
     * 批量删除管理员列表
     *
     * @param ids 需要删除的管理员列表主键
     * @return 结果
     */
    @Override
    public int deleteSysBizUserByIds(Long[] ids) {
        return sysBizUserMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除管理员列表信息
     *
     * @param id 管理员列表主键
     * @return 结果
     */
    @Override
    public int deleteSysBizUserById(Long id) {
        return sysBizUserMapper.deleteById(id);
    }

    /**
     * 是否存在该手机号
     *
     * @param userPhone 是否存在该手机号
     * @return 结果
     */
    @Override
    public boolean hasUserPhone(String userPhone) {
        LambdaQueryWrapper<SysBizUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizUser::getUserPhone, userPhone);
        queryWrapper.eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        List<SysBizUser> sysBizUsers = sysBizUserMapper.selectList(queryWrapper);
        return !sysBizUsers.isEmpty();
    }

    /**
     * 查询管理员列表
     *
     * @param sysBizUser 用户列表
     * @return 用户列表集合
     */
    @Override
    public List<SysBizUser> selectSysBizUserAdminList(SysBizUser sysBizUser) {
        return sysBizUserMapper.selectSysBizUserAdminList(sysBizUser);
    }

    /**
     * 审核
     *
     * @param sysBizUser 用户审核列表
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int processSysBizUser(SysBizUser sysBizUser) {
        sysBizUser.setUpdateTime(DateUtils.getNowDate());
        sysBizUser.setProcessTime(DateUtils.getNowDate());
        sysBizUser.setBindTime(DateUtils.getNowDate());
        if (sysBizUser.getProcessStatus().equals(ProcessStatusEnum.PASS_PROCESS.getKey())) {
            SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();
            LoginUser loginUser = SecurityUtils.getLoginUser();
            sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
            List<SysBizMemberGrade> sysBizMemberGradeList = sysBizMemberGradeService.list(new LambdaQueryWrapper<SysBizMemberGrade>().eq(SysBizMemberGrade::getGradeName, "经销商").eq(SysBizMemberGrade::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
            if (!sysBizMemberGradeList.isEmpty()) {
                sysBizUser.setMemberGradeId(sysBizMemberGradeList.get(0).getId());
            }
            sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
            sysBizOperationLog.setOperationItem(OperationItemEnum.ADD_MEMBERS.getKey());
            sysBizOperationLog.setOperationDetails("添加会员【" + sysBizUser.getUserPhone() + "】");
            sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
            sysBizOperationLogMapper.insert(sysBizOperationLog);
            sysBizUser.setUserRole(StandingEnum.IS_MEMBER.getKey());

        }
        int i = sysBizUserMapper.updateById(sysBizUser);
        if (sysBizUser.getProcessStatus().equals(ProcessStatusEnum.NOT_PASS_PROCESS.getKey())) {
            sysBizUserMapper.updateParentUserId(sysBizUser.getId());
            sysBizUserMapper.updateParentId(sysBizUser.getId());
        }
        return i;
    }


    /**
     * 查询用户审核列表
     *
     * @param sysBizUser 用户审核列表
     * @return 结果
     */
    @Override
    public List<SysBizUser> selectSysBizUserProcessList(SysBizUser sysBizUser) {
        return sysBizUserMapper.selectSysBizUserProcessList(sysBizUser);
    }

    /**
     * 查询用户列表(全部)
     *
     * @param sysBizUser 用户列表
     * @return 结果
     */
    @Override
    public List<SysBizUserVo> selectSysBizUserListAll(SysBizUser sysBizUser) {
        List<SysBizUserVo> sysBizUserVos = sysBizUserMapper.selectSysBizUserListAll(sysBizUser);
//        if (!CollectionUtils.isEmpty(sysBizUserVos)) {
//            for (SysBizUserVo sysBizUserVo : sysBizUserVos) {
//                if (sysBizUserVo.getUserRole() == 1 && StringUtils.isBlank(sysBizUserVo.getParentUserName())) {
//                    sysBizUserVo.setParentUserName("/");
//                }
//                // 查询已发展会员
//                long count = count(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getParentId, sysBizUserVo.getId()).eq(SysBizUser::getProcessStatus, 2).eq(SysBizUser::getVerifyStatus, 1));
//                sysBizUserVo.setDevelopedMembers(count);
//            }
//        }
        return sysBizUserVos;
    }

    /**
     * 查询用户列表(Child全部)
     *
     * @param sysBizUser 用户列表
     * @return 结果
     */
    @Override
    public List<SysBizUserVo> listChild(SysBizUser sysBizUser) {
        List<SysBizUserVo> sysBizUserVos = sysBizUserMapper.listChild(sysBizUser);
        if (!CollectionUtils.isEmpty(sysBizUserVos)) {
            for (SysBizUserVo sysBizUserVo : sysBizUserVos) {
                // 查询已发展会员
                long count = count(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getParentId, sysBizUserVo.getId()));
                sysBizUserVo.setDevelopedMembers(count);
            }
        }
        return sysBizUserVos;
    }


    /**
     * 查询会员团队核实列表
     *
     * @param sysBizUser 会员团队核实列表
     * @return 结果
     */
    @Override
    public List<SysBizUserVerifyVo> listVerify(SysBizUser sysBizUser) {
        List<SysBizUserVerifyVo> sysBizUserVerifyVos = sysBizUserMapper.listVerify(sysBizUser);
        if (!CollectionUtils.isEmpty(sysBizUserVerifyVos)) {
            for (SysBizUserVerifyVo sysBizUserVerifyVo : sysBizUserVerifyVos) {
                // 查询已发展会员
                long count = count(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getParentId, sysBizUserVerifyVo.getParentId()).eq(SysBizUser::getProcessStatus, 2).eq(SysBizUser::getVerifyStatus, 1));
                sysBizUserVerifyVo.setDevelopedMembersParent(count);
            }
        }
        return sysBizUserVerifyVos;
    }

    /**
     * 核实
     *
     * @param sysBizUser 用户列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editVerify(SysBizUser sysBizUser) {
        //加锁
        lock.lock();
        int i = 0;
        try {
            sysBizUser.setUpdateTime(DateUtils.getNowDate());
            sysBizUser.setVerifyTime(DateUtils.getNowDate());
            sysBizUser.setVerifyStatus(VerifyStatusEnum.APPROVED.getKey());
            sysBizUser.setProcessStatus(2);
            sysBizUser.setUserRole(1);
            sysBizUser.setProcessTime(DateUtils.getNowDate());
            SysBizUser user = sysBizUserMapper.selectById(sysBizUser.getId());
            if (user.getMemberGradeId() == null) {
                List<SysBizMemberGrade> sysBizMemberGradeList = sysBizMemberGradeService.list(new LambdaQueryWrapper<SysBizMemberGrade>().eq(SysBizMemberGrade::getGradeName, "经销商").eq(SysBizMemberGrade::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
                if (!sysBizMemberGradeList.isEmpty()) {
                    sysBizUser.setMemberGradeId(sysBizMemberGradeList.get(0).getId());
                }
            }
            i = sysBizUserMapper.updateById(sysBizUser);
            //如果核实通过的话
            if (i > 0) {
                //给上一级 可发展会员数减一
                SysBizUser sysBizUser1 = sysBizUserMapper.selectById(sysBizUser.getParentId());
                sysBizUser1.setUpdateTime(DateUtils.getNowDate());
                // 创建一个 AtomicInteger 对象，初始值为 sysBizUser1.getAvailableMembers()
                AtomicLong counter = new AtomicLong(sysBizUser1.getAvailableMembers());
                // 调用 decrementAndGet() 方法，将当前值减1并返回结果
                sysBizUser1.setAvailableMembers(counter.decrementAndGet());

                AtomicLong counter2 = new AtomicLong(sysBizUser1.getDevelopedMembers());
                // 调用 incrementAndGet() 方法，将当前值加1并返回结果
                sysBizUser1.setDevelopedMembers(counter2.incrementAndGet());
                sysBizUserMapper.updateById(sysBizUser1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            return i;
        }

    }

    /**
     * 查询用户列列表(上下级关系树)
     *
     * @param sysBizUser 用户列表
     * @return 结果
     */
    @Override
    public SysBizUserTreeVo upLowerLevel(SysBizUser sysBizUser) {
        SysBizUserTreeVo sysBizUserTreeVo = new SysBizUserTreeVo();
        sysBizUserTreeVo.setFindOut(true);
        List<SysBizUserVo> sysBizUserVos = sysBizUserMapper.upLowerLevel(sysBizUser);
        //如果没有找到对应的值 就查出全部
        if (sysBizUserVos.isEmpty()) {
            sysBizUserTreeVo.setFindOut(false);
            sysBizUser.setSearchValue(null);
            sysBizUserVos = sysBizUserMapper.upLowerLevel(sysBizUser);
        }
        List<Long> upList = new ArrayList<Long>();
        for (SysBizUserVo sysBizUserVo : sysBizUserVos) {
            if (sysBizUserVo.getParentId() != null) {
                //上级人数
                Long upLong = upLevel(sysBizUserVo.getId());
                sysBizUserVo.setUpNum(upLong);

                //上级数组
                List<Long> longs = upLevelList(sysBizUserVo.getId());
                upList.addAll(longs);
            }
            //下级人数
            Long downLong = downLevel(sysBizUserVo.getId());
            sysBizUserVo.setDownNum(downLong);
        }
        sysBizUserTreeVo.setSysBizUserVo(sysBizUserVos);
        sysBizUserTreeVo.setUpList(upList);
        return sysBizUserTreeVo;
    }

    public Long upLevel(Long userId) {
        Long num = 0L;
        SysBizUser sysBizUser = sysBizUserMapper.selectById(userId);
        if (sysBizUser.getParentId() != null) {
            SysBizUser user = sysBizUserMapper.selectById(sysBizUser.getParentId());
            num += 1;
            if (user != null) {
                num += upLevel(user.getId());
            }

        }
        return num;
    }

    public List<Long> upLevelList(Long userId) {
        List<Long> idList = new ArrayList<>();
        SysBizUser sysBizUser = sysBizUserMapper.selectById(userId);
        if (sysBizUser.getParentId() != null) {
            SysBizUser user = sysBizUserMapper.selectById(sysBizUser.getParentId());
            if (user != null) {
                idList.add(user.getId());
                idList.addAll(upLevelList(user.getId()));
            }
        }
        return idList;
    }

    public Long downLevel(Long userId) {
        long num = 0L;
        List<Long> sysBizUsers = sysBizUserMapper.selectObjs(new LambdaQueryWrapper<SysBizUser>().select(SysBizUser::getId).eq(SysBizUser::getParentId, userId)).stream().map(o -> (Long) o).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sysBizUsers)) {
            num += sysBizUsers.size();
            for (Long id : sysBizUsers) {
                num += downLevel(id);
            }
        }
        return num;
    }


    @Resource
    private SysBizShopCertificationMapper sysBizShopCertificationMapper;

    /**
     * 首页统计
     */
    @Override
    public UserVo queryUserById(Long userId) {
        SysBizUser sysBizUser = sysBizUserMapper.selectById(userId);
        UserVo userVo = new UserVo();
        List<SysBizShopCertification> sysBizShopCertifications = sysBizShopCertificationMapper.selectList(new LambdaQueryWrapper<SysBizShopCertification>()
                .eq(SysBizShopCertification::getUserId, userId)
                .eq(SysBizShopCertification::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));

        if (CollectionUtils.isEmpty(sysBizShopCertifications)) {
            userVo.setIsRole(0);
        } else {
            userVo.setIsRole(sysBizShopCertifications.get(0).getCertificationStatus());
        }
        BeanUtils.copyProperties(sysBizUser, userVo);
        // 查询优惠券数量
        LambdaQueryWrapper<SysBizCouponReceive> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysBizCouponReceive::getUserId, userId);
        queryWrapper.eq(SysBizCouponReceive::getTenantId, sysBizUser.getTenantId());
        queryWrapper.eq(SysBizCouponReceive::getStatus, 0);//查询未使用的优惠劵
        userVo.setCouponCount((int) sysBizCouponReceiveService.count(queryWrapper));

        if(sysBizUser.getIsSale().equals(1)){
            userVo.setIsRole(3);
        }

        // 如果已认证则查询店铺名称作为用户昵称
        if(userVo.getIsRole() == 3){
            if (!CollectionUtils.isEmpty(sysBizShopCertifications)) {
                userVo.setShopName(sysBizShopCertifications.get(0).getShopName());
            }else{
                userVo.setShopName(sysBizUser.getNickName());
            }
        }

        // 查询待付款订单
        LambdaQueryWrapper<SysBizOrder> sysBizOrderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizOrderLambdaQueryWrapper.eq(SysBizOrder::getUserId, userId);
        List<SysBizOrder> sysBizOrders = sysBizOrderService.selectSysBizOrderList(sysBizOrderLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(sysBizOrders)) {
            return userVo;
        }
        userVo.setObligation(sysBizOrders.stream().filter(i -> i.getStatus() == 10).count());
        userVo.setDelivery(sysBizOrders.stream().filter(i -> i.getStatus() == 20).count());
        userVo.setReceived(sysBizOrders.stream().filter(i -> i.getStatus() == 30).count());
        userVo.setEvaluated(sysBizOrders.stream().filter(i -> i.getStatus() == 40).count());

        return userVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void withdrawal(SysBizUser sysBizUser, BigDecimal amount) {
        sysBizUser.setUnwithdrawnBalance(sysBizUser.getUnwithdrawnBalance().subtract(amount));
//        sysBizUser.setWithdrawnBalance(sysBizUser.getWithdrawnBalance().add(amount));
        sysBizUser.setUpdateBy(sysBizUser.getNickName());
        sysBizUser.setUpdateTime(DateUtils.getNowDate());
        sysBizUserMapper.updateById(sysBizUser);
        // 新增提现记录
        long time = DateUtils.getNowDate().getTime();
        String uniqueId = StringUtils.leftPad(sysBizUser.getId().toString(), 8, "0") + time;
        String code = "TX" + uniqueId;
        SysBizWithdrawApply sysBizWithdrawApply = getSysBizWithdrawApply(sysBizUser, amount, code);
        sysBizWithdrawApplyService.save(sysBizWithdrawApply);
    }

    private static SysBizWithdrawApply getSysBizWithdrawApply(SysBizUser sysBizUser, BigDecimal amount, String code) {
        SysBizWithdrawApply sysBizWithdrawApply = new SysBizWithdrawApply();
        sysBizWithdrawApply.setUserId(sysBizUser.getId());
        sysBizWithdrawApply.setPaymentStatus(0);
        sysBizWithdrawApply.setUserName(sysBizUser.getNickName());
        sysBizWithdrawApply.setWithdrawalAmount(amount);
        sysBizWithdrawApply.setWithdrawCode(code);
        sysBizWithdrawApply.setBankBranch(sysBizUser.getBankBranch());
        sysBizWithdrawApply.setBankName(sysBizUser.getBankName());
        sysBizWithdrawApply.setBankUserName(sysBizUser.getBankUserName());
        sysBizWithdrawApply.setBankCardNumber(sysBizUser.getBankCardNumber());
        sysBizWithdrawApply.setPhone(sysBizUser.getBankPhone());
        sysBizWithdrawApply.setProcessStatus(1);
        sysBizWithdrawApply.setCreateTime(DateUtils.getNowDate());
        sysBizWithdrawApply.setCreateBy(sysBizUser.getNickName());
        return sysBizWithdrawApply;
    }


    //商品订单
    @Resource
    private SysBizOrderGoodsMapper sysBizOrderGoodsMapper;
    //活动订单
    @Resource
    private SysBizActivityEnrollMapper sysBizActivityEnrollMapper;
    //会员订单
    @Resource
    private SysBizWithdrawApplyMapper sysBizWithdrawApplyMapper;

    /**
     * 首页统计
     */
    @Override
    public OverviewVo overview(OverviewDto overviewDto) {
        OverviewVo overviewVo = new OverviewVo();

        //当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = sdf.format(date);

        OverviewDto overview = new OverviewDto();
        overview.setStartTime(DateUtils.dateTime2(DateUtils.getNowDate()));
        overview.setEndTime(DateUtils.dateTime2(DateUtils.getNowDate()));

        // 今日订单数量  （商品订单、会员订单、活动订单）
        //商品订单总数
        Long OrderGoods = sysBizOrderGoodsMapper.todayOrderCount(overview);
        //活动订单总数
        Long ActivityEnroll = sysBizActivityEnrollMapper.todayOrderCount(overview);
        //会员订单总数
        //Long DevelopOrder = sysBizDevelopOrderMapper.todayOrderCount(overviewDto);
        overviewVo.setTodayOrderCount(OrderGoods + ActivityEnroll);


        // 今日总收款 也就是当日订单的总金额（商品订单、活动订单）
        //商品订单总金额
        BigDecimal orderGoodsAmount = sysBizOrderGoodsMapper.PlatformTotalOrderAmount(overview);
        //活动订单总金额
        BigDecimal activityEnrollAmount = sysBizActivityEnrollMapper.PlatformTotalOrderAmount(overview);
        overviewVo.setTodayTotalRevenue(orderGoodsAmount.add(activityEnrollAmount));

        // 今日提现金额
        BigDecimal bigDecimal = sysBizWithdrawApplyMapper.todayWithdrawal(overview);
        overviewVo.setTodayWithdrawal(bigDecimal);


        // 平台总订单数量
        //商品订单总数
        Long OrderGoods1 = sysBizOrderGoodsMapper.todayOrderCount(overviewDto);
        //活动订单总数
        Long ActivityEnroll1 = sysBizActivityEnrollMapper.todayOrderCount(overviewDto);
        //会员订单总数
        //Long DevelopOrder = sysBizDevelopOrderMapper.todayOrderCount(overviewDto);
        overviewVo.setPlatformTotalOrderCount(OrderGoods1 + ActivityEnroll1);

        // 平台累计订单金额
        //商品金额
        BigDecimal orderGoodsAmount1 = sysBizOrderGoodsMapper.PlatformTotalOrderAmountAll(overviewDto);
        //活动订单总数
        BigDecimal activityEnrollAmount1 = sysBizActivityEnrollMapper.PlatformTotalOrderAmount(overviewDto);
        //会员订单总数
        //BigDecimal developOrderAmount = sysBizDevelopOrderMapper.PlatformTotalOrderAmount(overviewDto);
        overviewVo.setPlatformTotalOrderAmount(orderGoodsAmount1.add(activityEnrollAmount1));

        // 招商会员数
        Integer memberCount = sysBizUserMapper.temberCount(overviewDto);
        overviewVo.setMemberCount(memberCount);

        // 累计提现总额
        BigDecimal withdrawApply = sysBizWithdrawApplyMapper.todayWithdrawal(overviewDto);
        overviewVo.setTotalWithdrawalAmount(withdrawApply);

        // 累计余额总数
        BigDecimal totalBalance = sysBizUserMapper.totalBalance(overviewDto);
        overviewVo.setTotalBalance(totalBalance);

        return overviewVo;
    }

    @Resource
    private SysBizImportFailMapper sysBizImportFailMapper;


    @Value("${idCard.appCode}")
    private String appCode;

    @Value("${idCard.url}")
    private String url;

    /**
     * 批量注册会员
     */
    @Override
    public int importUser(List<SysBizUser> userList, boolean updateSupport, String operName) throws IOException {
        int failureNum = 0;
        if (StringUtils.isNull(userList) || userList.isEmpty() || userList.stream().allMatch(Objects::isNull)) {
            failureNum = -1;
            return failureNum;
        }

        for (SysBizUser user : userList) {
            SysBizImportFail sysBizImportFail = new SysBizImportFail();
            LoginUser loginUser = getLoginUser();
            sysBizImportFail.setUserId(loginUser.getUserId());
            sysBizImportFail.setType(ImportFailEnum.REGISTER_MEMBER_IMPORT.getKey());
            if (StringUtils.isBlank(user.getUserPhone())) {
                sysBizImportFail.setFailureReason("手机号码不能为空");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            sysBizImportFail.setUserPhone(user.getUserPhone());
            if (user.getUserPhone().length() != 11 || !user.getUserPhone().matches("^1[3-9]\\d{9}$")) {
                sysBizImportFail.setFailureReason("手机号码不合法");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            if (StringUtils.isBlank(user.getFullName())) {
                sysBizImportFail.setFailureReason("姓名不能为空");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            if (StringUtils.isBlank(user.getGradeName())) {
                sysBizImportFail.setFailureReason("会员等级不能为空");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }

            if (user.getGradeName().length() > 50) {
                sysBizImportFail.setFailureReason("会员等级不能超过50字符");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }

            SysBizMemberGrade sysBizMemberGrade = sysBizMemberGradeService.getOne(new LambdaQueryWrapper<>(SysBizMemberGrade.class).eq(SysBizMemberGrade::getGradeName, user.getGradeName()).eq(SysBizMemberGrade::getDeleted, 0));
            if (sysBizMemberGrade == null) {
                sysBizImportFail.setFailureReason("会员等级不存在");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
            if (sysBizMemberGrade.getDisplayed() == 1) {
                sysBizImportFail.setFailureReason("会员等级已下架");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }
//            if (StringUtils.isBlank(user.getIdCard())) {
//                sysBizImportFail.setFailureReason("身份证号不能为空");
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }


            // 实名验证start
//            Map<String, String> params = new HashMap<>();
//            params.put("idcard", user.getIdCard());
//            params.put("name", user.getFullName());
//            String result = postForm(appCode, url, params);
//            JSONObject resultData = JSON.parseObject(result);
//            if (!"0".equals(resultData.get("code"))) {
//                sysBizImportFail.setFailureReason(resultData.get("message").toString());
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }
//            JSONObject jsonObject = JSON.parseObject(resultData.get("result").toString());
//            if ("2".equals(jsonObject.get("res").toString())) {
//                sysBizImportFail.setFailureReason("姓名与身份证号不一致");
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }
//            if (!"1".equals(jsonObject.get("res").toString())) {
//                sysBizImportFail.setFailureReason(jsonObject.get("description").toString());
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }
//            List<SysBizUser> users = sysBizUserMapper.selectList(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getIdCard,
//                    user.getIdCard()));
//            if (!CollectionUtils.isEmpty(users)) {
//                sysBizImportFail.setFailureReason("身份证号码已存在");
//                sysBizImportFailMapper.insert(sysBizImportFail);
//                failureNum++;
//                continue;
//            }
            // 实名验证end

            // 验证手机号是否存在
            if (this.hasUserPhone(user.getUserPhone())) {
                // 判断是否是会员
                LambdaQueryWrapper<SysBizUser> sysBizUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysBizUserLambdaQueryWrapper.eq(SysBizUser::getUserPhone, user.getUserPhone());
                sysBizUserLambdaQueryWrapper.eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
                SysBizUser sysBizUser = sysBizUserMapper.selectOne(sysBizUserLambdaQueryWrapper);
                if (sysBizUser.getUserRole().equals(StandingEnum.IS_MEMBER.getKey())) {
                    sysBizImportFail.setFailureReason("该手机号已经是会员");
                    sysBizImportFailMapper.insert(sysBizImportFail);
                    failureNum++;
                    continue;
                } else {
                    sysBizUser.setUserRole(StandingEnum.IS_MEMBER.getKey());
                    sysBizUser.setFullName(user.getFullName());
                    sysBizUser.setIdCard(user.getIdCard());
                    sysBizUser.setMemberGradeId(sysBizMemberGrade.getId());
                    user.setCreateBy(operName);
                    sysBizUser.setIsRegisterMember(1);
                    sysBizUser.setProcessStatus(ProcessStatusEnum.PASS_PROCESS.getKey());
                    sysBizUser.setVerifyStatus(1);
                    sysBizUser.setVerifyTime(DateUtils.getNowDate());
                    sysBizUser.setProcessTime(DateUtils.getNowDate());
                    if (StringUtils.isNotBlank(user.getParentPhone())) {
                        SysBizUser parentUser = sysBizUserMapper.selectOne(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getUserPhone, user.getParentPhone()).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
                        if (parentUser == null) {
                            sysBizImportFail.setFailureReason("未找到推荐人");
                            sysBizImportFailMapper.insert(sysBizImportFail);
                            failureNum++;
                            continue;
                        }
                        sysBizUser.setParentId(parentUser.getId());
                    }
                    sysBizUserMapper.updateById(sysBizUser);
                    // 等级变更记录
                    String oldGradeName = "";
                    String newGradeName = sysBizMemberGrade.getGradeName();
                    sysBizGradeLogService.save(SysBizGradeLog.builder().userId(sysBizUser.getId()).gradeIdOld(null).gradeIdNew(sysBizUser.getMemberGradeId()).gradeNameOld(oldGradeName).gradeNameNew(newGradeName).createBy(SecurityUtils.getUsername()).createTime(DateUtils.getNowDate()).build());

                    //日志表
                    SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();
                    sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
                    sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
                    sysBizOperationLog.setOperationItem(OperationItemEnum.ADD_MEMBERS.getKey());
                    sysBizOperationLog.setOperationDetails("添加会员【" + sysBizUser.getUserPhone() + "】");
                    sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
                    sysBizOperationLogMapper.insert(sysBizOperationLog);
                    sysBizUserMapper.updateById(sysBizUser);
                    continue;
                }
            } else {
                // 新增
                SysBizUser sysBizUser = new SysBizUser();
                sysBizUser.setUserRole(StandingEnum.IS_MEMBER.getKey());
                sysBizUser.setUserPhone(user.getUserPhone());
                sysBizUser.setIdCard(user.getIdCard());
                sysBizUser.setDisplayed(0);
                sysBizUser.setIsRegisterMember(1);
                sysBizUser.setCreateBy(operName);
                sysBizUser.setMemberGradeId(sysBizMemberGrade.getId());
                sysBizUser.setCreateTime(DateUtils.getNowDate());
                sysBizUser.setProcessStatus(ProcessStatusEnum.PASS_PROCESS.getKey());
                sysBizUser.setProcessTime(DateUtils.getNowDate());
                sysBizUser.setVerifyStatus(1);
                sysBizUser.setVerifyTime(DateUtils.getNowDate());
                sysBizUser.setFullName(user.getFullName());
                sysBizUser.setIdCard(user.getIdCard());
                sysBizUser.setPassword(SecurityUtils.encryptPassword(user.getUserPhone()));
                if (StringUtils.isNotBlank(user.getParentPhone())) {
                    SysBizUser parentUser = sysBizUserMapper.selectOne(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getUserPhone, user.getParentPhone()).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
                    if (parentUser == null) {
                        sysBizImportFail.setFailureReason("未找到推荐人");
                        sysBizImportFailMapper.insert(sysBizImportFail);
                        failureNum++;
                        continue;
                    }
                    sysBizUser.setParentId(parentUser.getId());
                }
                String KEY = "INVITATION_CODE";
                List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
                if (!CollectionUtils.isEmpty(list) && list.size() >= 9999999) {
                    log.error("邀请码满员");
                }
                String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
                if (!CollectionUtils.isEmpty(list)) {
                    do {
                        code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
                    } while (list.contains(code) || Objects.equals(code, user.getInvitationCode()));
                }
                redisTemplate.opsForList().leftPush(KEY, code);
                sysBizUser.setInvitationCode(code);
                sysBizUserMapper.insert(sysBizUser);
                sysBizUserMapper.updateBizId(sysBizUser.getId());
                // 等级变更记录
                String oldGradeName = "";
                String newGradeName = sysBizMemberGrade.getGradeName();
                sysBizGradeLogService.save(SysBizGradeLog.builder().userId(sysBizUser.getId()).gradeIdOld(null).gradeIdNew(sysBizUser.getMemberGradeId()).gradeNameOld(oldGradeName).gradeNameNew(newGradeName).createBy(SecurityUtils.getUsername()).createTime(DateUtils.getNowDate()).build());
                //日志表
                SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();
                sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
                sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
                sysBizOperationLog.setOperationItem(OperationItemEnum.ADD_MEMBERS.getKey());
                sysBizOperationLog.setOperationDetails("添加会员【" + sysBizUser.getUserPhone() + "】");
                sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
                sysBizOperationLogMapper.insert(sysBizOperationLog);
            }

        }
        return failureNum;
    }

    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        for (String key : params.keySet()) {
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    /**
     * 批量充值金额
     */
    @Override
    public int registerImportData(List<SysBizUser> userList, boolean updateSupport, String operName) {
        int failureNum = 0;
        if (StringUtils.isNull(userList) || userList.isEmpty() || userList.stream().allMatch(Objects::isNull)) {
            failureNum = -1;
            return failureNum;
        }
        for (SysBizUser user : userList) {
            SysBizImportFail sysBizImportFail = new SysBizImportFail();
            LoginUser loginUser = getLoginUser();
            sysBizImportFail.setUserId(loginUser.getUserId());
            sysBizImportFail.setType(ImportFailEnum.RECHARGE_IMPORT.getKey());
            sysBizImportFail.setUserPhone(user.getUserPhone());
            sysBizImportFail.setRechargeBalance(user.getRechargeBalance().toString());
            if (user.getUserPhone().isEmpty() || user.getUserPhone().length() > 11) {
                sysBizImportFail.setFailureReason("手机号不能为空和长度不能超过11位");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            } else if (user.getRechargeBalance() == null || !isValidDecimal(user.getRechargeBalance().toString())) {
                sysBizImportFail.setFailureReason("充值余额不能为空和整数不能超过9位数小数点后不能超过两位数");
                sysBizImportFailMapper.insert(sysBizImportFail);
                failureNum++;
                continue;
            }

            // 验证手机号是否存在
            if (this.hasUserPhone(user.getUserPhone())) {
                LambdaQueryWrapper<SysBizUser> sysBizUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                sysBizUserLambdaQueryWrapper.eq(SysBizUser::getUserPhone, user.getUserPhone());
                SysBizUser sysBizUser = sysBizUserMapper.selectOne(sysBizUserLambdaQueryWrapper);
                if (sysBizUser.getUserRole().equals(StandingEnum.UN_MEMBER.getKey())) {
                    sysBizImportFail.setFailureReason("该用户不是会员");
                    sysBizImportFailMapper.insert(sysBizImportFail);
                    failureNum++;
                    continue;
                } else {
                    BigDecimal rechargeBalance = null;
                    try {
                        rechargeBalance = sysBizUser.getRechargeBalance().add(user.getRechargeBalance());
                    } catch (Exception e) {
                        failureNum++;
                        sysBizImportFail.setFailureReason("充值余额格式不正确");
                        sysBizImportFailMapper.insert(sysBizImportFail);
                        continue;
                    }


                    //日志表
                    SysBizOperationLog sysBizOperationLog = new SysBizOperationLog();

                    sysBizOperationLog.setTenantId(loginUser.getTenantId());
                    sysBizOperationLog.setOperator(loginUser.getUser().getNickName());
                    sysBizOperationLog.setIpAddress(loginUser.getIpaddr() + "(" + IpUtils.getLocation(loginUser.getIpaddr()) + ")");
                    sysBizOperationLog.setOperationItem(OperationItemEnum.MEMBER_RECHARGE.getKey());
                    sysBizOperationLog.setOperationDetails("会员充值【" + user.getUserPhone() + "+￥" + user.getRechargeBalance() + "】");
                    sysBizOperationLog.setOperationTime(DateUtils.getNowDate());
                    sysBizOperationLogMapper.insert(sysBizOperationLog);

                    sysBizUser.setRechargeBalance(rechargeBalance);
                    sysBizUserMapper.updateById(sysBizUser);
                    continue;
                }
            } else {
                failureNum++;
                sysBizImportFail.setFailureReason("该手机号还没注册");
                sysBizImportFailMapper.insert(sysBizImportFail);
            }
        }
        return failureNum;
    }

    public static boolean isValidDecimal(String input) {
        String regex = "^\\d{1,9}(\\.\\d{1,2})?$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        return matcher.matches();
    }

    @Override
    public void updateMemberInfoByNull(Long userId) {
        sysBizUserMapper.updateMemberInfoByNull(userId);
    }

    /**
     * 修改管理员列表
     */
    @Override
    public int updateSysBizUserAdmin(SysBizUser sysBizUser) {
        sysBizUser.setUpdateTime(DateUtils.getNowDate());
        return sysBizUserMapper.updateById(sysBizUser);
    }

    @Override
    public List<SysBizUserExportVo> selectSysBizUserListExportAll(SysBizUser sysBizUser) {
        return sysBizUserMapper.selectSysBizUserListExportAll(sysBizUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysBizUser login(WxMaPhoneNumberInfo phoneNoInfo, WxLoginDto entity) throws ServiceException {
        LambdaQueryWrapper<SysBizUser> sysBizUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizUserLambdaQueryWrapper.eq(SysBizUser::getUserPhone, phoneNoInfo.getPhoneNumber());
        sysBizUserLambdaQueryWrapper.eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        List<SysBizUser> sysBizUsers = sysBizUserMapper.selectList(sysBizUserLambdaQueryWrapper);
        String token = TokenUtils.createToken();
        if (CollectionUtils.isEmpty(sysBizUsers)) {
            SysBizUser sysBizUser = new SysBizUser();
            sysBizUser.setAvatar(entity.getAvatar());
            sysBizUser.setDisplayed(BizUserStatusEnum.OK.getKey());
            sysBizUser.setNickName(entity.getNickName());
            sysBizUser.setOpenId(entity.getOpenId());
            sysBizUser.setCreateTime(DateUtils.getNowDate());
            sysBizUser.setIsRegisterMember(1);
            sysBizUser.setScore(0L);
            sysBizUser.setGrade(0L);
            if (entity.getInviteUserId() != null && entity.getInviteUserId() != null) {
                sysBizUser.setParentId(entity.getInviteUserId());
                sysBizUser.setParentUserId(entity.getInviteUserId());
            }

            sysBizUser.setIsAdmin(0);
            sysBizUser.setUserRole(1);
            sysBizUser.setCreateTime(new Date());
            sysBizUser.setDeleted(0);
            sysBizUser.setUseScore(0L);
            sysBizUser.setFrozenScore(0L);
            sysBizUser.setDisplayed(0);
            sysBizUser.setUserPhone(phoneNoInfo.getPhoneNumber());
            // 查询是否白名单
            LambdaQueryWrapper<SysBizUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysBizUser::getUserPhone, phoneNoInfo.getPhoneNumber());
            wrapper.eq(SysBizUser::getIsAdmin, IsAdminEnum.ADMINISTRATOR.getKey());
            SysBizUser bizUser = sysBizUserMapper.selectOne(wrapper);
            sysBizUser.setToken(token);
            // 如果是白名单管理员，执行修改操作
            if (bizUser != null) {
                if (bizUser.getDisplayed().equals(BizUserStatusEnum.DISABLE.getKey())) {
                    throw new ServiceException("该账号已被禁用");
                }
                sysBizUser.setId(bizUser.getId());
                sysBizUser.setIsAdmin(IsAdminEnum.ADMINISTRATOR.getKey());
//                if (StringUtils.isBlank(sysBizUser.getInvitationCode())) {
//                    // 生成邀请码
//                    SysBizUser user = sysBizUserMapper.selectById(1L);
//                    String KEY = "INVITATION_CODE";
//                    List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
//
//                    sysBizUserMapper.insert(sysBizUser);
//                    TokenCache.setMpData(token, JSON.toJSONString(sysBizUser));
//                    sysBizUserMapper.updateBizId(sysBizUser.getId());
//                    if (!CollectionUtils.isEmpty(list) && list.size() >= 9999999) {
//                        log.error("邀请码满员");
//
//
//                    } else {
//                        String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                        if (!CollectionUtils.isEmpty(list)) {
//                            do {
//                                code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                            } while (list.contains(code) || Objects.equals(code, user.getInvitationCode()));
//                        }
//                        redisTemplate.opsForList().leftPush(KEY, code);
//                        sysBizUser.setInvitationCode(code);
//                    }
//                }
                sysBizUserMapper.updateById(sysBizUser);


                TokenCache.setMpData(token, JSON.toJSONString(sysBizUser));
                log.info("================{}", token);
                sysBizUser.setToken(token);
                return sysBizUser;
            }

            log.info("================{}", token);
            sysBizUser.setToken(token);
            // 生成邀请码
//            SysBizUser user = sysBizUserMapper.selectById(1L);
//            String KEY = "INVITATION_CODE";
//            List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
//            if (!CollectionUtils.isEmpty(list) && list.size() >= 9999999) {
//                log.error("邀请码满员");
//                sysBizUserMapper.insert(sysBizUser);
//                TokenCache.setMpData(token, JSON.toJSONString(sysBizUser));
//                sysBizUserMapper.updateBizId(sysBizUser.getId());
//                return sysBizUser;
//            }
//            String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//            if (!CollectionUtils.isEmpty(list)) {
//                do {
//                    code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                } while (list.contains(code) || Objects.equals(code, user.getInvitationCode()));
//            }
//            redisTemplate.opsForList().leftPush(KEY, code);
//            sysBizUser.setInvitationCode(code);
            sysBizUserMapper.insert(sysBizUser);
            TokenCache.setMpData(token, JSON.toJSONString(sysBizUser));
            sysBizUserMapper.updateBizId(sysBizUser.getId());
            return sysBizUser;
        } else if (sysBizUsers.size() == 1) {
            SysBizUser sysBizUser = sysBizUsers.get(0);
            sysBizUser.setOpenId(entity.getOpenId());
//            if (StringUtils.isBlank(sysBizUser.getInvitationCode())) {
//                SysBizUser user = sysBizUserMapper.selectById(1L);
//                // 生成邀请码
//                String KEY = "INVITATION_CODE";
//                List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
//                if (!CollectionUtils.isEmpty(list) && list.size() >= 9000000) {
//                    log.error("邀请码满员");
//                    sysBizUserMapper.insert(sysBizUser);
//                    return sysBizUser;
//                }
//                String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                if (!CollectionUtils.isEmpty(list)) {
//                    do {
//                        code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                    } while (list.contains(code) || Objects.equals(code, user.getInvitationCode()));
//                }
//                redisTemplate.opsForList().leftPush(KEY, code);
//                sysBizUser.setInvitationCode(code);
//            }
            if (sysBizUser.getDisplayed().equals(BizUserStatusEnum.DISABLE.getKey())) {
                throw new ServiceException("该账号已被禁用");
            }
//            sysBizUser.setAvatar(entity.getAvatar());
//            sysBizUser.setNickName(entity.getNickName());
            sysBizUserMapper.updateById(sysBizUser);
            TokenCache.setMpData(token, JSON.toJSONString(sysBizUser));
            sysBizUser.setToken(token);
            return sysBizUser;
        } else {
            throw new ServiceException("用户信息异常，存在多个openId或电话号码");
        }
    }

    @Autowired
    private ISysBizTenantService tenantService;

    @Override
    public SysBizUser registerUser(RegisterMemberDto registerMemberDto) throws ServiceException {
        SysBizUser sysBizUser = new SysBizUser();
        Snowflake snowflake = IdUtil.getSnowflake();


        SysBizTenant sysBizTenant = tenantService.selectSysBizTenantByDefault();
        sysBizUser.setTenantId(0L);
        if (sysBizTenant != null) {

            sysBizUser.setTenantId(sysBizTenant.getId());
        } else {
            log.info("未配置默认站点");
        }
        long id = ShortSnowflakeUtils.nextId();
        sysBizUser.setId(id);
        //sysBizUser.setFullName(registerMemberDto.getFullName());
        sysBizUser.setMemberPhone(registerMemberDto.getMemberPhone());
        //sysBizUser.setIdCard(registerMemberDto.getIdCard());
        //sysBizUser.setRemark(registerMemberDto.getRemark());


        sysBizUser.setDisplayed(BizUserStatusEnum.OK.getKey());
        String encryptPassword = SecurityUtils.encryptPassword(registerMemberDto.getPassword());

        sysBizUser.setPassword(encryptPassword);
        sysBizUser.setCreateTime(DateUtils.getNowDate());
        sysBizUser.setIsRegisterMember(1);
        sysBizUser.setScore(0L);
        sysBizUser.setGrade(0L);

        sysBizUser.setIsAdmin(0);
        sysBizUser.setUserRole(1);
        sysBizUser.setUpdateTime(new Date());
        sysBizUser.setDeleted(0);
        sysBizUser.setUseScore(0L);
        sysBizUser.setFrozenScore(0L);
        sysBizUser.setDisplayed(0);
        sysBizUser.setUserPhone(registerMemberDto.getMemberPhone());
        String token = TokenUtils.createToken();
        sysBizUser.setToken(token);

        sysBizUser.setProcessStatus(ProcessStatusEnum.UN_PROCESS.getKey());
        sysBizUser.setAuthenticationStatus(0);

        sysBizUser.setScore(0L);
        saveOrUpdate(sysBizUser);
        TokenCache.setMpData(token, JSON.toJSONString(sysBizUser));
        sysBizUser.setToken(token);

        sysBizUserMapper.updateBizId(sysBizUser.getId());
        return sysBizUser;
    }

    /**
     * 递归查询用户所有的下级Id集合
     */
    @Override
    public List<Long> findBySubordinate(SysBizUser sysBizUser) {
        List<SysBizUser> sysBizUsers = sysBizUserMapper.selectList(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getParentId, sysBizUser.getId()).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
        if (!CollectionUtils.isEmpty(sysBizUsers)) {
            List<Long> idList = sysBizUsers.stream().map(SysBizUser::getId).collect(Collectors.toList());
            for (SysBizUser bizUser : sysBizUsers) {
                idList.addAll(findBySubordinate(bizUser));
            }
            return idList;
        }
        return new ArrayList<>();
    }

    /**
     * 递归查询用户所有的上级Id集合
     */
    @Override
    public List<Long> findBySuperior(SysBizUser sysBizUser) {
        List<Long> idList = new ArrayList<>();
        if (sysBizUser.getParentId() != null) {
            SysBizUser user = sysBizUserMapper.selectById(sysBizUser.getParentId());
            if (user != null) {
                idList.add(user.getId());
                idList.addAll(findBySuperior(user));
            }
        }
        return idList;
    }


    /**
     * 充值金额
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int surplusPUT(SysBizUser sysBizUser) {
        SysBizUser sysBizUser1 = sysBizUserMapper.selectById(sysBizUser.getId());
        BigDecimal add;
        BigDecimal surplus = sysBizUser.getSurplus();
        if (sysBizUser.getType() == 0) {
            add = sysBizUser1.getSurplus().add(sysBizUser.getSurplus());
        } else if (sysBizUser1.getSurplus().compareTo(sysBizUser.getSurplus()) < 0) {
            throw new ServiceException("余额不足");
        } else {
            add = sysBizUser1.getSurplus().subtract(sysBizUser.getSurplus());
        }
        //用户表新增值
        sysBizUser.setSurplus(add);
        int i = sysBizUserMapper.updateById(sysBizUser);

        //用户充值表新增
        SysBizRechargeUser sysBizRechargeUser = new SysBizRechargeUser();
        String orderCode = OrderNoCreate.surplusOrderCode(OrderTypeEnum.SURPLUS.name());
        sysBizRechargeUser.setOrderId(orderCode);
        sysBizRechargeUser.setUserId(sysBizUser1.getId());
        sysBizRechargeUser.setRechargePrice(surplus);
        sysBizRechargeUser.setGivePrice(BigDecimal.valueOf(0.00));
        sysBizRechargeUser.setTenantId(sysBizUser1.getTenantId());
        sysBizRechargeUser.setRechargeBalanceBefore(sysBizUser1.getSurplus());
        sysBizRechargeUser.setRechargeBalanceAfter(add);
        sysBizRechargeUser.setPaymentStatus(1);   //已支付
        sysBizRechargeUser.setRechargeSource(2); //平台
        sysBizRechargeUser.setAuditStatus(1);
        sysBizRechargeUser.setStatus(40);
        sysBizRechargeUser.setCreateTime(DateUtils.getNowDate());
        sysBizRechargeUser.setPayTime(DateUtils.getNowDate());
        sysBizRechargeUserMapper.insert(sysBizRechargeUser);

        //用户余额明细表新增
        SysBizUserSurplusDetails sysBizUserSurplusDetails = new SysBizUserSurplusDetails();
        sysBizUserSurplusDetails.setUserId(sysBizUser1.getId());
        sysBizUserSurplusDetails.setTenantId(sysBizUser1.getTenantId());
        sysBizUserSurplusDetails.setOrderId(orderCode);
        sysBizUserSurplusDetails.setType(sysBizUser.getType()); //新增
        sysBizUserSurplusDetails.setRechargePrice(surplus);
        sysBizUserSurplusDetails.setPrice(surplus);
        sysBizUserSurplusDetails.setSource(2);
        sysBizUserSurplusDetailsMapper.insert(sysBizUserSurplusDetails);


        return i;
    }

    @Override
    public List<UpLowerLevelExportVo> selectUpLowerLevelExport() {
        List<SysBizUser> sysBizUsers = sysBizUserMapper.selectList(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getDeleted, 0));
        if (!CollectionUtils.isEmpty(sysBizUsers)) {
            List<Long> idList = new ArrayList<>();
            List<SysBizUser> userList = new ArrayList<>();
            for (SysBizUser sysBizUser : sysBizUsers) {
                if (idList.contains(sysBizUser.getId())) {
                    continue;
                }
                idList.add(sysBizUser.getId());
                userList.add(sysBizUser);
                List<Long> bySubordinate = findBySubordinate(sysBizUser);
                if (!CollectionUtils.isEmpty(bySubordinate)) {
                    List<Long> collect = bySubordinate.stream().distinct().filter(x -> !idList.contains(x)).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        idList.addAll(collect);
                        List<SysBizUser> sysBizUserList = sysBizUserMapper.selectBatchIds(collect);
                        userList.addAll(sysBizUserList);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(userList)) {
                List<UpLowerLevelExportVo> upLowerLevelExportVos = new ArrayList<>();
                for (SysBizUser sysBizUser : userList) {
                    UpLowerLevelExportVo upLowerLevelExportVo = new UpLowerLevelExportVo();
                    upLowerLevelExportVo.setFullName(StringUtils.isBlank(sysBizUser.getFullName()) ? sysBizUser.getNickName() : sysBizUser.getFullName());
                    upLowerLevelExportVo.setMemberPhone(sysBizUser.getUserPhone());
                    if (sysBizUser.getMemberGradeId() != null) {
                        SysBizMemberGrade sysBizMemberGrade = sysBizMemberGradeService.getById(sysBizUser.getMemberGradeId());
                        upLowerLevelExportVo.setGrade(sysBizMemberGrade == null ? "" : sysBizMemberGrade.getGradeName());
                    }
                    if (sysBizUser.getParentId() != null) {
                        // 查询上级
                        SysBizUser user = sysBizUserMapper.selectById(sysBizUser.getParentId());
                        if (user != null) {
                            upLowerLevelExportVo.setParentFullName(StringUtils.isBlank(user.getFullName()) ? user.getNickName() : user.getFullName());
                            upLowerLevelExportVo.setParentMemberPhone(StringUtils.isBlank(user.getMemberPhone()) ? user.getUserPhone() : user.getMemberPhone());
                            if (user.getMemberGradeId() != null) {
                                SysBizMemberGrade sysBizMemberGrade = sysBizMemberGradeService.getById(user.getMemberGradeId());
                                upLowerLevelExportVo.setParentGradeName(sysBizMemberGrade == null ? "" : sysBizMemberGrade.getGradeName());
                            }
                        }
                    }
                    Long upLong = upLevel(sysBizUser.getId());
                    upLowerLevelExportVo.setUpNum(upLong);
                    Long downLong = downLevel(sysBizUser.getId());
                    upLowerLevelExportVo.setDownNum(downLong);
                    upLowerLevelExportVos.add(upLowerLevelExportVo);
                }
                return upLowerLevelExportVos;
            }
        }
        return Collections.emptyList();
    }

    @Override
    public SysBizUser verificationCode(VerificationCodeLoginDto verificationCodeLoginDto) {
        SysBizUser user = sysBizUserMapper.selectOne(new LambdaQueryWrapper<SysBizUser>().eq(SysBizUser::getUserPhone, verificationCodeLoginDto.getPhoneNumber()).eq(SysBizUser::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()));
        String token = TokenUtils.createToken();
        if (user == null) {
            throw new ServiceException("用户不存在,请先注册");
        } else {
//            if (StringUtils.isBlank(user.getInvitationCode())) {
//                SysBizUser bizUser = sysBizUserMapper.selectById(1L);
//                // 生成邀请码
//                String KEY = "INVITATION_CODE";
//                List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
//                if (!CollectionUtils.isEmpty(list) && list.size() >= 9000000) {
//                    log.error("邀请码满员");
//                    sysBizUserMapper.insert(user);
//                    return user;
//                }
//                String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                if (!CollectionUtils.isEmpty(list)) {
//                    do {
//                        code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                    } while (list.contains(code) || Objects.equals(code, bizUser.getInvitationCode()));
//                }
//                redisTemplate.opsForList().leftPush(KEY, code);
//                user.setInvitationCode(code);
//            }
            if (user.getDisplayed().equals(BizUserStatusEnum.DISABLE.getKey())) {
                throw new ServiceException("该账号已被禁用");
            }
            user.setIsToSetPassword(false);
            if (StringUtils.isBlank(user.getPassword())) {
                user.setIsToSetPassword(true);
            }
            sysBizUserMapper.updateById(user);
            TokenCache.setMpData(token, JSON.toJSONString(user));
            user.setToken(token);
            oldUser(user.getId());
            return user;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysBizUser loginByPassword(PasswordLoginDto passwordLoginDto, SysBizUser user) {
        if (!SecurityUtils.matchesPassword(passwordLoginDto.getPassword(), user.getPassword())) {
            throw new ServiceException("用户名或密码输入错误");
        }
        if (user.getDisplayed().equals(BizUserStatusEnum.DISABLE.getKey())) {
            throw new ServiceException("该账号已被禁用");
        }
//        if (StringUtils.isBlank(user.getInvitationCode())) {
//            SysBizUser bizUser = sysBizUserMapper.selectById(1L);
//            // 生成邀请码
//            String KEY = "INVITATION_CODE";
//            List<String> list = redisTemplate.opsForList().range(KEY, 0, -1);
//            if (!CollectionUtils.isEmpty(list) && list.size() >= 9000000) {
//                log.error("邀请码满员");
//                sysBizUserMapper.insert(user);
//                return user;
//            }
//            String code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//            if (!CollectionUtils.isEmpty(list)) {
//                do {
//                    code = String.format("%8d", 10000000 + new Random().nextInt(90000000));
//                } while (list.contains(code) || Objects.equals(code, bizUser.getInvitationCode()));
//            }
//            redisTemplate.opsForList().leftPush(KEY, code);
//            user.setInvitationCode(code);
//        }
        sysBizUserMapper.updateById(user);
        String token = TokenUtils.createToken();
        TokenCache.setMpData(token, JSON.toJSONString(user));
        user.setToken(token);
        oldUser(user.getId());
        return user;
    }


    public void oldUser(Long userId) {
        SysBizUser sysBizUser = sysBizUserMapper.selectById(userId);
        if(sysBizUser!=null){
            //查询老系统的用户优惠券 (通过手机号)  返回优惠券code 和余额
            String getUserUrlStr = HttpUtils.sendGet(getUserUrl, "mobile=" + sysBizUser.getUserPhone() + "&token=74be16979710d4c4e7c6647856088456", Constants.UTF8);
            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(getUserUrlStr);
            int code = jsonResponse.getIntValue("code");

            //老系统查到该用户 但是新系统没有认证过
            if(code==200 && sysBizUser.getIsOldUser() == null){
                String jsonArrayString = jsonResponse.getString("data");
                ExternalOldUserDto externalOldUserDto = JSON.parseObject(jsonArrayString, ExternalOldUserDto.class);
                //更新用户金额
                sysBizUserMapper.update(new SysBizUser(),new LambdaUpdateWrapper<SysBizUser>()
                        .eq(SysBizUser::getId, sysBizUser.getId())
                        .set(SysBizUser::getIsOldUser, 0)
                        .set(SysBizUser::getTenantId,2L)
                        .set(externalOldUserDto.getBalance()!=null,SysBizUser::getSurplus, sysBizUser.getSurplus().add(externalOldUserDto.getBalance()))
                );
                //用户认证信息
                ExternalMerchantDto merchant = externalOldUserDto.getMerchant();

                //查看店铺是否认证过
                List<SysBizShopCertification> sysBizShopCertifications = sysBizShopCertificationService.selectSysBizShopCertificationList(new LambdaQueryWrapper<SysBizShopCertification>()
                        .eq(SysBizShopCertification::getUserId, sysBizUser.getId())
                        .eq(SysBizShopCertification::getDeleted,0)
                );
                //旧系统认证过 但是新系统没有认证
                if(merchant!=null &&  merchant.getIsState()!=null && merchant.getIsState() ==5
                        && StringUtils.isNotBlank(merchant.getMerchantName())
                        && CollectionUtils.isEmpty(sysBizShopCertifications)){
                    SysBizShopCertification sysBizShopCertification = new SysBizShopCertification();
                    sysBizShopCertification.setUserId(sysBizUser.getId());
                    sysBizShopCertification.setTenantId(2L); //无锡
                    sysBizShopCertification.setShopName(merchant.getMerchantName());
                    sysBizShopCertification.setIdCard("1");
                    sysBizShopCertification.setShopCover(StringUtils.isEmpty(merchant.getPicture())?"无":merchant.getPicture()); //店铺头像
                    sysBizShopCertification.setShopType(StringUtils.isEmpty(merchant.getMerchantType())?"无":merchant.getMerchantType());
                    sysBizShopCertification.setCertificationStatus(3);  //状态
                    sysBizShopCertification.setApplyTime(LocalDateTime.now());
                    sysBizShopCertification.setAuditTime(LocalDateTime.now());
                    sysBizShopCertification.setContacts(sysBizUser.getUserPhone()); //联系人
//                        sysBizShopCertification.setIdFrontPic();  //身份证正面图片
//                        sysBizShopCertification.setIdBackPic(); //身份证反面图片
//                    sysBizShopCertification.setBussCertificatePics(merchant.getPicture()); //营业执照图片
                    sysBizShopCertification.setProvince("江苏省");// 省市 默认无锡
                    sysBizShopCertification.setCity("无锡市");
                    sysBizShopCertification.setArea(!StringUtils.isEmpty(merchant.getAddress()) ? merchant.getAddress().substring(merchant.getAddress().indexOf("市") + 1).trim().isEmpty() ? "无" : merchant.getAddress().substring(merchant.getAddress().indexOf("市") + 1).trim() : "无");
                    sysBizShopCertification.setAddress( StringUtils.isEmpty(merchant.getAddressInfo())?"无":merchant.getAddressInfo());
                    sysBizShopCertificationService.save(sysBizShopCertification);
                }
                //用户优惠券可用
                List<ExternalCouponOldDto> couponList = externalOldUserDto.getCouponList();
                if(!CollectionUtils.isEmpty(couponList)){
                    for (ExternalCouponOldDto coupon : couponList) {
                        // 查询优惠券信息
                        SysBizCoupon sysBizCoupon = sysBizCouponMapper.selectOne(
                                new LambdaQueryWrapper<SysBizCoupon>().eq(SysBizCoupon::getUid, coupon.getCouponCode())
                        );
                        if(sysBizCoupon==null){
                            continue;
                        }
                        SysBizCouponGrant sysBizCouponGrant = new SysBizCouponGrant();
                        // 复制查询到的优惠券信息到grant对象中
                        BeanUtils.copyProperties(sysBizCoupon, sysBizCouponGrant);
                        // 设置创建时间和发放时间
                        sysBizCouponGrant.setGrantNum((long)coupon.getGetlimit());
                        sysBizCouponGrant.setId(null);
                        sysBizCouponGrant.setCouponId(sysBizCoupon.getId());
                        sysBizCouponGrant.setCreateTime(DateUtils.getNowDate());
                        sysBizCouponGrant.setGrantTime(DateUtils.getNowDate());
                        // 插入优惠券发放记录
                        sysBizCouponGrantMapper.insert(sysBizCouponGrant);

                        // 分发优惠券给用户
                        distributeCouponToUser(sysBizCoupon, sysBizCouponGrant, sysBizUser.getUserPhone());
                    }
                }

                //迁移成功后 发送给用户迁移成功
                HttpUtils.sendPost(returnUrl, "mobile=" + sysBizUser.getUserPhone() + "&token=74be16979710d4c4e7c6647856088456");
            }

        }
    }


    private void distributeCouponToUser(SysBizCoupon sysBizCoupon, SysBizCouponGrant sysBizCouponGrant, String userPhone){
        // 查询用户信息
        List<SysBizUser> sysBizUsers = sysBizUserMapper.selectList(new LambdaQueryWrapper<>(SysBizUser.class).eq(SysBizUser::getUserPhone, userPhone));

//        for (int i = 0; i < sysBizCouponGrant.getGrantNum(); i++) {

            SysBizCouponGrantUser sysBizCouponGrantUser = new SysBizCouponGrantUser();
            sysBizCouponGrantUser.setGrantId(sysBizCouponGrant.getId());
            sysBizCouponGrantUser.setPhone(userPhone);
            sysBizCouponGrantUser.setGrantTime(DateUtils.getNowDate());

            // 检查优惠券剩余数量
            if (sysBizCoupon.getSurplusNum() <= 0) {
                sysBizCouponGrantUser.setFailReason("优惠券数量不足");
                sysBizCouponGrantUser.setGrantResult(GrantResultEnum.FAIL.getKey());
                sysBizCouponGrantUserMapper.insert(sysBizCouponGrantUser);
                return;
            }

            // 获取用户信息，这里假设第一个匹配的用户即为有效用户
            SysBizUser sysBizUser = !sysBizUsers.isEmpty() ? sysBizUsers.get(0) : null;

            // 检查用户是否存在
            if (sysBizUser == null) {
                sysBizCouponGrantUser.setGrantResult(GrantResultEnum.FAIL.getKey());
                sysBizCouponGrantUser.setFailReason("未查询到该手机号用户");
                sysBizCouponGrantUserMapper.insert(sysBizCouponGrantUser);
                return;
            }

            if (!sysBizUser.getTenantId().equals(sysBizCoupon.getTenantId())) {
                sysBizCouponGrantUser.setGrantResult(GrantResultEnum.FAIL.getKey());
                sysBizCouponGrantUser.setFailReason("该用户站点和优惠券站点不统一");
                sysBizCouponGrantUser.setUserName(sysBizUser.getNickName());
                sysBizCouponGrantUserMapper.insert(sysBizCouponGrantUser);
                return;
            }

            // 更新优惠券发放状态（使用事务保证数据一致性）
            updateCouponAndInsertReceiveRecord(sysBizCoupon, sysBizUser, null, sysBizCouponGrant);

            // 设置发放成功
            sysBizCouponGrantUser.setGrantResult(GrantResultEnum.SUCCESS.getKey());
            sysBizCouponGrantUser.setUserName(sysBizUser.getNickName());
            sysBizCouponGrantUserMapper.insert(sysBizCouponGrantUser);

//        }
    }


    private SysBizCouponReceive updateCouponAndInsertReceiveRecord(SysBizCoupon sysBizCoupon, SysBizUser sysBizUser, SysBizCouponReceive sysBizCouponReceive, SysBizCouponGrant sysBizCouponGrant){
        // 使用事务处理优惠券的发放和记录插入
        if (sysBizCoupon.getSurplusNum() <= 0) {
//            throw new Exception("优惠券已领完");
            return null;
        }
        sysBizCoupon.setIssueNum(sysBizCoupon.getIssueNum() + 1);
        sysBizCoupon.setSurplusNum(sysBizCoupon.getSurplusNum() - 1);
        sysBizCouponMapper.updateSysBizCoupon(sysBizCoupon);
        if (sysBizCouponReceive == null) {
            sysBizCouponReceive = createCouponReceiveRecord(sysBizUser, sysBizCouponGrant, sysBizCoupon);
        }
        if(sysBizCoupon.getNewCoupon()==1){
            sysBizCouponReceive.setNewCoupon(1);
        }
        sysBizCouponReceiveMapper.insert(sysBizCouponReceive);
        return sysBizCouponReceive;
    }

    private SysBizCouponReceive createCouponReceiveRecord(SysBizUser sysBizUser, SysBizCouponGrant sysBizCouponGrant, SysBizCoupon sysBizCoupon) {
        SysBizCouponReceive sysBizCouponReceive = new SysBizCouponReceive();
        BeanUtils.copyProperties(sysBizCouponGrant, sysBizCouponReceive);
        sysBizCouponReceive.setId(null);
        sysBizCouponReceive.setSourceType(0);
        sysBizCouponReceive.setCouponId(sysBizCoupon.getId());
        sysBizCouponReceive.setUserId(sysBizUser.getId());
        sysBizCouponReceive.setUserName(sysBizUser.getNickName());
        sysBizCouponReceive.setPhone(sysBizUser.getUserPhone());
        sysBizCouponReceive.setCouponName(sysBizCoupon.getName());
        sysBizCouponReceive.setReceiveTime(DateUtils.getNowDate());
        sysBizCouponReceive.setScopeUse(sysBizCoupon.getScopeUse());
        calculateExpiration(sysBizCouponReceive);
        return sysBizCouponReceive;
    }

    private void calculateExpiration(SysBizCouponReceive sysBizCouponReceive) {
        // 计算优惠券过期时间
        if (sysBizCouponReceive.getValidityType() == 2) {
            String date = DateUtils.getDate();
            Date beginTime = DateUtils.addDays(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 00:00:00"), Math.toIntExact(sysBizCouponReceive.getReceivingDay()));
            sysBizCouponReceive.setTermBeginTime(beginTime);
            Date endTime = DateUtils.addDays(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 23:59:59"), Math.toIntExact(sysBizCouponReceive.getReceivingDay() + sysBizCouponReceive.getEffectiveDay()));
            sysBizCouponReceive.setTermEndTime(endTime);
        } else {
            String date = DateUtils.dateTime(sysBizCouponReceive.getTermEndTime());
            sysBizCouponReceive.setTermEndTime(DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, date + " 23:59:59"));
        }
    }


    @Override
    public void updatePassword(UpdatePasswordDto updatePasswordDto, SysBizUser sysBizUser) {
        String encryptPassword = SecurityUtils.encryptPassword(updatePasswordDto.getPassword());
        sysBizUser.setPassword(encryptPassword);
        sysBizUserMapper.updateById(sysBizUser);
    }

    @Override
    public List<DevelopUserP2Vo> queryDevelopUserP2(DevelopUserP2Dto developUserP2Dto, Integer level, Long userId) {
        return sysBizUserMapper.queryDevelopUserP2(developUserP2Dto, level, userId);
    }

    @Override
    public List<SysBizUser> listUserSales(SysBizUser sysBizUser) {
        return sysBizUserMapper.listUserSales(sysBizUser);
    }
}


